package com.yy.ttmodule.utils;


import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.location.GpsStatus;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;

import com.yy.ttmodule.control.Constant;

import java.lang.ref.WeakReference;

public class GPSLocationManager implements
        LocationListener, GpsStatus.Listener, GpsStatus.NmeaListener {

    private static GPSLocationManager gpsLocationManager;

    private static Object objLock = new Object();
    private WeakReference<Activity> mContext;
    private LocationManager mLocationManager;

    int gpsStatus = -1;
    double longitude;//经度
    String longitudeHem;
    double latitude;//纬度
    String latitudeHem;
    double altitude;//海拔

    public static GPSLocationManager getInstances(Activity context) {
        if (gpsLocationManager == null) {
            synchronized (objLock) {
                if (gpsLocationManager == null) {
                    gpsLocationManager = new GPSLocationManager(context);
                }
            }
        }
        return gpsLocationManager;
    }

    private GPSLocationManager(Activity context) {
        initData(context);
    }

    private void initData(Activity context) {
        this.mContext = new WeakReference<>(context);
        if (mContext.get() != null) {
            mLocationManager = (LocationManager) (mContext.get().getSystemService(Context.LOCATION_SERVICE));
        }

        String GPSProvider = LocationManager.GPS_PROVIDER;
        Location location = mLocationManager.getLastKnownLocation(GPSProvider);
        if ( location != null ) {
            double longitude = location.getLongitude();
            double altitude = location.getAltitude();
            Logger.d("getLastKnownLocation: longitude = " + longitude + ", altitude = " + altitude);
        }

        mLocationManager.addNmeaListener(this);
        mLocationManager.addGpsStatusListener(this);
        mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 0, this);
    }

    @Override
    public void onNmeaReceived(long timestamp, String nmea) {
        Logger.d("GPGGA","获取的GPGGA数据是："+nmea);
        if ( nmea.contains("GPGGA") ) {
            String info[] = nmea.split(",");
            Logger.d("GPGGA","获取的GPGGA数据是："+nmea);
            Logger.i("GPGGA","纬度："+info[2]);
            Logger.i("GPGGA","纬度半球："+info[3]);
            Logger.i("GPGGA","经度："+info[4]);
            Logger.i("GPGGA","经度半球："+info[5]);
            Logger.i("GPGGA","GPS状态："+info[6]);
            Logger.i("GPGGA","椭球高："+info[9]);

            try {
                longitude = Double.parseDouble(info[4]);//经度
                longitudeHem = info[5];//E或W(东经或西经)
                latitude = Double.parseDouble(info[2]);//纬度
                latitudeHem = info[3];//N或S(北纬或南纬)
                altitude = Double.parseDouble(info[9]);//海拔
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void onLocationChanged(Location location) {
        Logger.d("GPGGA","onLocationChanged：" + location);
        longitude = location.getLongitude();
        latitude = location.getLatitude();
        altitude = location.getAltitude();
    }

    @Override
    public void onStatusChanged(String s, int i, Bundle bundle) {
        Logger.d("GPGGA","onStatusChanged：" + s);
    }

    @Override
    public void onGpsStatusChanged(int i) {
        Logger.d("GPGGA","onGpsStatusChanged：" + i);
        gpsStatus = i;
    }

    @Override
    public void onProviderEnabled(String s) {}
    @Override
    public void onProviderDisabled(String s) {}

    public void openGPS() {
        if (Build.VERSION.SDK_INT > 15) {
            Intent intent = new Intent(
                    Settings.ACTION_LOCATION_SOURCE_SETTINGS);
            mContext.get().startActivityForResult(intent, 0);
        }/*
        if (ActivityCompat.checkSelfPermission(mContext.get(), Manifest.permission.ACCESS_FINE_LOCATION) !=
                PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(mContext.get(),
                Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            return;
        }*/
    }

    public void stop() {
        if (mContext.get() != null) {
            mLocationManager.removeUpdates(this);
        }
    }

    public byte[] getGpsData() {
        byte[] res = new byte[]{Constant.EXC_FAILURE};
        try {
            if ( gpsStatus > 0 ) {
                res = new byte[8 + 1 + 8 + 1 + 8];
                appendArrayDoubleData(res, 0, latitude);
                res[8] = (byte) (latitude > 0 ? 0x4E : 0x53);//0x4E:N 0x53:S
                appendArrayDoubleData(res, 9, longitude);
                res[17] = (byte) (longitude > 0 ? 0x45 : 0x57);//0x45 E 0x57：W
                appendArrayDoubleData(res, 18, altitude);

                /*appendArrayDoubleData(res, 0, latitude);
                res[8] = (byte) (latitudeHem.equals("N") ? 0x4E : 0x53);
                appendArrayDoubleData(res, 9, longitude);
                res[17] = (byte) (longitudeHem.equals("E") ? 0x45 : 0x57);
                appendArrayDoubleData(res, 18, altitude);*/
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return res;
    }

    public void appendArrayDoubleData(byte[] b, int offset, double data) {
        long value = Double.doubleToRawLongBits(data);
        for (int i = 0; i < 8; i++) {
            b[offset + i] =  (byte) ((value >> 8 * i) & 0xff);
        }
    }

    //https://blog.csdn.net/qq_19688207/article/details/105990444
    //http://www.taodudu.cc/news/show-2076624.html?action=onClick
    //https://cloud.tencent.com.cn/developer/article/1727027
    //https://blog.51cto.com/u_16213571/8242535
    //https://blog.csdn.net/HZHXH/article/details/70038092/
    //https://cloud.tencent.com/developer/ask/sof/102891871
    //https://www.xjx100.cn/news/667899.html?action=onClick//GPS,GPGGA,NMEA-0183,RTCM 单位解析


    //https://www.cnblogs.com/catcher92/p/4518391.html
    //http://www.uwenku.com/question/p-aiivmcdh-to.html
    //http://cn.voidcc.com/question/p-drutvzof-bdv.html
    //https://cloud.tencent.com/developer/ask/sof/102891871

    /*private class LocationListenerImpl implements LocationListener {
        @Override
        public void onLocationChanged(Location location) {
            if ( location != null ) {
                Logger.i("GPGGA","getLatitude："+ location.getLatitude() + ", getLongitude:" +
                        location.getLongitude() + ", getAltitude: " + location.getAltitude());
            }
        }

        @Override
        public void onStatusChanged(String provider, int status, Bundle extras) {
            Logger.i("GPGGA","status："+ status);
        }

        @Override
        public void onProviderEnabled(String provider) {
        }

        @Override
        public void onProviderDisabled(String provider) {
        }
    }*/
}
